package com.cyys.modules.system.service.org;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyys.common.services.CyysBaseService;
import com.cyys.modules.system.dao.org.OrgBranchDao;
import com.cyys.modules.system.model.org.Org;
import com.cyys.modules.system.model.org.OrgBranch;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service("orgBranchService")
@Transactional(readOnly = true)
public class OrgBranchService extends CyysBaseService<OrgBranchDao, OrgBranch> {

	/**
	 * 维护机构关系
	 */
	@Transactional(rollbackFor = Exception.class)
	public void insertOrgBranch(Org org) {
		// 增加机构关系表
		List<OrgBranch> relationList = dao.selectList(
				Wrappers.<OrgBranch>query().lambda().eq(OrgBranch::getOrgId, org.getParentId()))
				.stream().map(relation -> {
					relation.setId(null);
					relation.setOrgId(org.getId());
					return relation;
				}).collect(Collectors.toList());
		if (CollUtil.isNotEmpty(relationList)) {
			dao.insertBatchSomeColumn(relationList);
		}

		// 自己也要维护到关系表中
		OrgBranch own = new OrgBranch();
		own.setOrgId(org.getId());
		own.setParentId(org.getParentId());
		dao.insert(own);
	}


	/**
	 * 通过ID删除机构关系(注意这里的orgId只针对于没有子节点的机构)
	 * @param orgIds
	 */
	public void deleteAllOrgBranch(String[] orgIds) {
		dao.deleteOrgBranchByOrgId(orgIds);
	}

	/**
	 * 更新机构关系
	 * @param relation
	 */
	public void updateOrgBranch(OrgBranch relation) {
		dao.delOrgBranchs(relation);
		dao.insertOrgBranchs(relation);
	}
}
